package com.justgame.project.mq.consumer.system;

import com.justgame.mq.client.constant.SystemQueueConstant;
import com.justgame.project.cloud.common.constant.Const;
import com.justgame.project.cloud.common.util.RabbitHelper;
import com.justgame.project.cloud.common.util.RedisUtils;
import com.justgame.project.cloud.common.util.ShiroUtils;
import com.rabbitmq.client.Channel;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * @author ZhouWeiBo
 * @create 2022/5/30
 */
@Slf4j
@Component
@AllArgsConstructor
public class UserLogoutConsumer {
    private final RedisUtils redisUtils;

    @RabbitHandler
    @RabbitListener(queues = SystemQueueConstant.SYSTEM_USER_LOGOUT_QUEUE)
    public void processUserLogout(Channel channel, Message message) throws IOException {
        try {
            String token = new String(message.getBody());
            Long userId = null;
            if (StringUtils.isBlank(token) || null ==( userId = ShiroUtils.getUserIdByToken(token) )) {
                return;
            }
            log.info("UserId【{}】：已退出登录，正在处理后续业务...", userId);
            ShiroUtils.delToken(token, userId);
            redisUtils.delete(Const.KEY_REDIS_USER + userId);
            log.info("UserId【{}】：退出登录后续业务处理完毕！", userId);
            RabbitHelper.execute(message);
        } catch (Exception e) {
            e.printStackTrace();
            RabbitHelper.receive(message,e);
        } finally {
            // ACK
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        }
    }
}
